//
//  WCXMPPTool.m
//  WeChat
//
//  Created by lin on 15/7/21.
//  Copyright (c) 2015年 lin. All rights reserved.
//

#import "WCXMPPTool.h"
/*
 * 在AppDelegate实现登录
 
 1. 初始化XMPPStream
 2. 连接到服务器[传一个JID]
 3. 连接到服务成功后，再发送密码授权
 4. 授权成功后，发送"在线" 消息
 */
@interface WCXMPPTool ()<XMPPStreamDelegate>{
    XMPPStream *_xmppStream;
    XMPPResultBlock _resultBlock;
}

// 1. 初始化XMPPStream
-(void)setupXMPPStream;


// 2.连接到服务器
-(void)connectToHost;

// 3.连接到服务成功后，再发送密码授权
-(void)sendPwdToHost;


// 4.授权成功后，发送"在线" 消息
-(void)sendOnlineToHost;
@end

@implementation WCXMPPTool
singleton_implementation(WCXMPPTool);



#pragma mark  -私有方法
#pragma mark 初始化XMPPStream
-(void)setupXMPPStream{
    
    _xmppStream = [[XMPPStream alloc] init];
    
    // 设置代理
    [_xmppStream addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
}

#pragma mark 连接到服务器
-(void)connectToHost{
    WCLog(@"开始连接到服务器");
    if (!_xmppStream) {
        [self setupXMPPStream];
    }
    
    NSString *usr =  nil;
    if (self.registerOperation) {
        usr = [WCUserInfo sharedWCUserInfo].registerUsr;
    }else{
        usr= [WCUserInfo sharedWCUserInfo].usr;
    }
    
    // 设置登录用户JID
    //resource 标识用户登录的客户端 iphone android
    XMPPJID *myJID = [XMPPJID jidWithUser:usr domain:@"lin.local" resource:@"iphone" ];
    _xmppStream.myJID = myJID;
    // 设置服务器域名
    _xmppStream.hostName = @"lin.local";//不仅可以是域名，还可是IP地址
    // 设置端口 如果服务器端口是5222，可以省略
    _xmppStream.hostPort = 5222;
    // 连接
    NSError *err = nil;
    if(![_xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&err]){
        WCLog(@"%@",err);
    }
    
    
    
}


#pragma mark 连接到服务成功后，再发送密码授权
-(void)sendPwdToHost{
    WCLog(@"再发送密码授权");
    //从单例中取出密码
    NSString *pwd =[WCUserInfo sharedWCUserInfo].pwd;
    NSError *err = nil;
    [_xmppStream authenticateWithPassword:pwd error:&err];
    if (err) {
        WCLog(@"%@",err);
    }
}

#pragma mark  授权成功后，发送"在线" 消息
-(void)sendOnlineToHost{
    
    WCLog(@"发送 在线 消息");
    XMPPPresence *presence = [XMPPPresence presence];
    WCLog(@"%@",presence);
    if (_resultBlock) {
        _resultBlock(XMPPResultTypeLoginSuccess);
    }
    [_xmppStream sendElement:presence];
    
    
}
#pragma mark -XMPPStream的代理
#pragma mark 与主机连接成功
-(void)xmppStreamDidConnect:(XMPPStream *)sender{
    WCLog(@"与主机连接成功");
    if (self.registerOperation) {
        NSString *registerPwd = [WCUserInfo sharedWCUserInfo].registerPwd;
        NSError *err;
        [_xmppStream registerWithPassword:registerPwd error:&err];
    }
    // 主机连接成功后，发送密码进行授权
    [self sendPwdToHost];
    
    //连接成功有可能发送注册的密码
}
#pragma mark  与主机断开连接
-(void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error{
    if (error && _resultBlock) {
        _resultBlock(XMPPResultTypeNetErr);
    }
    // 如果有错误，代表连接失败
    WCLog(@"与主机断开连接 %@",error);
    
}


#pragma mark 授权成功
-(void)xmppStreamDidAuthenticate:(XMPPStream *)sender{
    WCLog(@"授权成功");
    [self sendOnlineToHost];
}


#pragma mark 授权失败
-(void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement *)error{
    WCLog(@"授权失败 %@",error);
    if (_resultBlock) {
        _resultBlock(XMPPResultTypeLoginFailure);
    }
}

#pragma mark  注册成功
-(void)xmppStreamDidRegister:(XMPPStream *)sender{
    if (_resultBlock) {
        _resultBlock(XMPPResultTypeRegisterSuccess);
    }
    WCLog(@"注册成功");
}
#pragma mark  注册失败
-(void)xmppStream:(XMPPStream *)sender didNotRegister:(DDXMLElement *)error{
    if (_resultBlock) {
        _resultBlock(XMPPResultTypeRegisterFailure);
    }
    WCLog(@"注册失败");
}

#pragma mark -公共方法
-(void)logout{
    // 1." 发送 "离线" 消息"
    XMPPPresence *offline = [XMPPPresence presenceWithType:@"unavailable"];
    [_xmppStream sendElement:offline];
    
    // 2. 与服务器断开连接
    [_xmppStream disconnect];
}

#pragma mark login
-(void)xmppUserLogin:(XMPPResultBlock)resultBlock{
    //断开之前的连接
    [_xmppStream disconnect];
    _resultBlock = resultBlock;
    
    [self connectToHost];
}

-(void)xmppUserLogout{
    //发送离线消息
    XMPPPresence *offline = [XMPPPresence presenceWithType:@"umavailable"];
    [_xmppStream sendElement:offline];
    
    //断开之前的连接
    [_xmppStream disconnect];
    
    //回到主界面
  //  self.window.rootViewController = [UIStoryboard storyboardWithName:@"Login" bundle:nil].instantiateInitialViewController;
    //更改用户的登录状态
    [UIStoryboard showInitialVCWithName:@"Login"];
    
    [WCUserInfo sharedWCUserInfo].loginStatus = NO;
    [[WCUserInfo sharedWCUserInfo] saveUserInfoToSandbox];
    [self connectToHost];
}

//用户注册
-(void)xmppUserRegister:(XMPPResultBlock)resultBlock{
    //断开之前的连接
    [_xmppStream disconnect];
    _resultBlock = resultBlock;
    //连接到主机，发送密码
    [self connectToHost];
    
    
    
}



@end
